package service

import (
	"errors"
	"go_stu_gin/middleware"
	"go_stu_gin/util"
	viewmodel "go_stu_gin/view_model"
	"io"
	"os"

	"github.com/gin-gonic/gin"
)

type PublicService struct{}

func (p *PublicService) Login(ctx *gin.Context) (int, string, error) {
	var input viewmodel.LoginInput
	if err := util.DefaultBindParams(ctx, &input); err != nil {
		return util.NOTFOUND, "", err
	}
	claims := &middleware.JWTClaims{
		Id:   1,
		Name: input.Name,
	}
	token, err := middleware.CreateToken(claims)
	if err != nil {
		return util.NOTFOUND, "", err
	}
	return util.SUCCESS, token, nil
}

func (p *PublicService) Download(ctx *gin.Context) (int, error) {
	var input viewmodel.DownloadInput
	if err := util.DefaultBindParams(ctx, &input); err != nil {
		return util.NOTFOUND, err
	}
	if input.Name == "" {
		return util.NOTFOUND, errors.New("输入要下载的文件名")
	}
	path := "./public/"
	fileName := input.Name
	f, err := os.Open(path + fileName)
	if err != nil {
		return util.NOTFOUND, err
	}
	defer f.Close()
	ctx.Header("content-type", "application/stream")
	ctx.Header("content-disposition", "attachment;filename="+fileName)
	// ctx.File("./config/yaml/conf_dev.yaml")
	_, _ = io.Copy(ctx.Writer, f)
	return util.SUCCESS, nil
}
